package com.lxhotel.agentmcp.filter;

import com.lxhotel.agentmcp.context.WebContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;

import static com.lxhotel.agentmcp.context.WebContext.USER_ID_KEY;

/**
 * This class function is xxx.
 *
 * @author yangbo
 * @date 2025/09/29
 */
@Component
@Slf4j
public class WebAuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader(USER_ID_KEY);
        log.info("校验用户:{}", userId);
        if (ObjectUtils.isEmpty(userId)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        WebContext.setUserId(Long.valueOf(userId));
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        WebContext.remove();
    }
}